package com.msblearn.C_005;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 共享锁：ReadWirteLock：对读的时候时共享的，运行线程同时读，当时write的时候，
 * 只运行一个线程写。读线程也要等待。当时读的时候，写也要在等待
 *
 * 排他锁：只能一个线程读或写，其他的线程都在等待。
 */
public class T05_ReadWriteLock {
    //排他锁。
    private static Lock lock = new ReentrantLock();
    private static  int value;


    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static  Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock){
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public static  void write(Lock lock,int v){
        try {
            lock.lock();
            Thread.sleep(1000);
            value = v;
            System.out.println("write over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
//        Runnable readR = ()->read(lock);
        Runnable readR =()->read(readLock);

//        Runnable writeR = ()->write(lock, new Random().nextInt());
        Runnable writeR =()->write(writeLock,new Random().nextInt());
        for(int i=0;i<18;i++){
            new Thread(readR).start();
        }
        for(int i=0;i<2;i++){
            new Thread(writeR).start();
        }
    }
}



